<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>大模型配置 - YOLO训练平台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .config-card {
            transition: transform 0.2s;
        }
        .config-card:hover {
            transform: translateY(-2px);
        }
        .active-config {
            border: 2px solid #28a745;
            background-color: #f8fff9;
        }
        .password-field {
            position: relative;
        }
        .password-toggle {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="{{ url_for('main.index') }}">
                <i class="fas fa-robot me-2"></i>YOLO训练平台
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="{{ url_for('main.index') }}">首页</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-brain me-2"></i>大模型配置</h2>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#configModal">
                        <i class="fas fa-plus me-2"></i>添加配置
                    </button>
                </div>

                <!-- 配置列表 -->
                <div class="row" id="configList">
                    <!-- 配置卡片将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 配置模态框 -->
    <div class="modal fade" id="configModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加LLM配置</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="configForm">
                        <input type="hidden" id="configId">
                        <div class="mb-3">
                            <label for="configName" class="form-label">配置名称</label>
                            <input type="text" class="form-control" id="configName" required>
                        </div>
                        <div class="mb-3">
                            <label for="baseUrl" class="form-label">Base URL</label>
                            <input type="url" class="form-control" id="baseUrl" placeholder="https://api.openai.com/v1" required>
                            <div class="form-text">OpenAI兼容的API基础URL</div>
                        </div>
                        <div class="mb-3">
                            <label for="apiKey" class="form-label">API Key</label>
                            <div class="password-field">
                                <input type="password" class="form-control" id="apiKey">
                                <i class="fas fa-eye password-toggle" onclick="togglePassword('apiKey')"></i>
                            </div>
                            <div class="form-text">对于Ollama等本地模型，API Key可以为空</div>
                        </div>
                        <div class="mb-3">
                            <label for="modelName" class="form-label">模型名称</label>
                            <input type="text" class="form-control" id="modelName" placeholder="gpt-4-vision-preview" required>
                            <div class="form-text">支持视觉功能的模型名称</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveConfig()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 页面加载时获取配置列表
        document.addEventListener('DOMContentLoaded', function() {
            loadConfigs();
        });

        // 加载配置列表
        function loadConfigs() {
            fetch('/api/llm-configs')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayConfigs(data.configs);
                    } else {
                        showAlert('加载配置失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('加载配置失败', 'danger');
                });
        }

        // 显示配置列表
        function displayConfigs(configs) {
            const configList = document.getElementById('configList');
            if (configs.length === 0) {
                configList.innerHTML = `
                    <div class="col-12">
                        <div class="text-center py-5">
                            <i class="fas fa-brain fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">暂无LLM配置</h5>
                            <p class="text-muted">点击上方按钮添加第一个配置</p>
                        </div>
                    </div>
                `;
                return;
            }

            configList.innerHTML = configs.map(config => `
                <div class="col-md-6 col-lg-4 mb-3">
                    <div class="card config-card ${config.is_active ? 'active-config' : ''}">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h6 class="card-title mb-0">${config.name}</h6>
                                ${config.is_active ? '<span class="badge bg-success">当前激活</span>' : ''}
                            </div>
                            <p class="card-text small text-muted mb-2">
                                <i class="fas fa-link me-1"></i>${config.base_url}
                            </p>
                            <p class="card-text small text-muted mb-3">
                                <i class="fas fa-robot me-1"></i>${config.model}
                            </p>
                            <div class="btn-group w-100" role="group">
                                ${!config.is_active ? `<button class="btn btn-outline-success btn-sm" onclick="activateConfig(${config.id})">激活</button>` : ''}
                                <button class="btn btn-outline-primary btn-sm" onclick="editConfig(${config.id})">编辑</button>
                                <button class="btn btn-outline-danger btn-sm" onclick="deleteConfig(${config.id})">删除</button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 切换密码显示
        function togglePassword(fieldId) {
            const field = document.getElementById(fieldId);
            const toggle = field.nextElementSibling;
            
            if (field.type === 'password') {
                field.type = 'text';
                toggle.classList.remove('fa-eye');
                toggle.classList.add('fa-eye-slash');
            } else {
                field.type = 'password';
                toggle.classList.remove('fa-eye-slash');
                toggle.classList.add('fa-eye');
            }
        }

        // 保存配置
        function saveConfig() {
            const configId = document.getElementById('configId').value;
            const formData = {
                name: document.getElementById('configName').value,
                base_url: document.getElementById('baseUrl').value,
                api_key: document.getElementById('apiKey').value,
                model: document.getElementById('modelName').value
            };

            const url = configId ? `/api/llm-configs/${configId}` : '/api/llm-configs';
            const method = configId ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert(configId ? '配置更新成功' : '配置添加成功', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('configModal')).hide();
                    loadConfigs();
                    resetForm();
                } else {
                    showAlert('保存失败: ' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('保存失败', 'danger');
            });
        }

        // 编辑配置
        function editConfig(configId) {
            fetch(`/api/llm-configs/${configId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const config = data.config;
                        document.getElementById('configId').value = config.id;
                        document.getElementById('configName').value = config.name;
                        document.getElementById('baseUrl').value = config.base_url;
                        document.getElementById('apiKey').value = config.api_key;
                        document.getElementById('modelName').value = config.model;
                        document.getElementById('modalTitle').textContent = '编辑LLM配置';
                        new bootstrap.Modal(document.getElementById('configModal')).show();
                    } else {
                        showAlert('获取配置失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('获取配置失败', 'danger');
                });
        }

        // 激活配置
        function activateConfig(configId) {
            fetch(`/api/llm-configs/${configId}/activate`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('配置激活成功', 'success');
                    loadConfigs();
                } else {
                    showAlert('激活失败: ' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('激活失败', 'danger');
            });
        }

        // 删除配置
        function deleteConfig(configId) {
            if (confirm('确定要删除这个配置吗？')) {
                fetch(`/api/llm-configs/${configId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showAlert('配置删除成功', 'success');
                        loadConfigs();
                    } else {
                        showAlert('删除失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('删除失败', 'danger');
                });
            }
        }

        // 重置表单
        function resetForm() {
            document.getElementById('configForm').reset();
            document.getElementById('configId').value = '';
            document.getElementById('modalTitle').textContent = '添加LLM配置';
        }

        // 显示提示信息
        function showAlert(message, type) {
            // 移除之前的alert
            const existingAlerts = document.querySelectorAll('.alert');
            existingAlerts.forEach(alert => {
                if (alert.parentNode) {
                    alert.remove();
                }
            });
            
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show mt-3`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // 尝试多种插入方式
            try {
                const container = document.querySelector('.container');
                const row = container ? container.querySelector('.row') : null;
                
                if (container && row) {
                    container.insertBefore(alertDiv, row);
                } else if (container) {
                    container.insertBefore(alertDiv, container.firstChild);
                } else {
                    // 最后的备选方案
                    const body = document.body;
                    if (body.firstChild) {
                        body.insertBefore(alertDiv, body.firstChild);
                    } else {
                        body.appendChild(alertDiv);
                    }
                }
            } catch (error) {
                console.error('Alert insertion error:', error);
                // 如果所有方法都失败，使用简单的append
                document.body.appendChild(alertDiv);
            }
            
            setTimeout(() => {
                try {
                    if (alertDiv && alertDiv.parentNode) {
                        alertDiv.remove();
                    }
                } catch (error) {
                    console.error('Alert removal error:', error);
                }
            }, 5000);
        }

        // 模态框关闭时重置表单
        document.getElementById('configModal').addEventListener('hidden.bs.modal', function () {
            resetForm();
        });
    </script>
</body>
</html>